'use client';

import { formatCurrency } from '@/utils/common';
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';

const FilterPrice = ({
  title,
  type,
  datakey,
  data,
  basePath,
  filtersData,
  onChange,
  loginTipsVisible,
  defaultCollapse,
}: FilterSectionProps) => {
  const [expand, setExpand] = useState(
    loginTipsVisible && defaultCollapse != undefined ? !defaultCollapse : true
  );
  const [maxPrice, setMaxPrice] = useState<string>('');
  const [minPrice, setMinPrice] = useState<string>('');

  const toogleExpand = () => {
    setExpand(e => !e);
  };

  const [loginURL, setLoginURL] = useState('');
  const [signupURL, setSignupURL] = useState('');
  const getLoginURL = () => {
    const url =
      process.env.NEXT_PUBLIC_LOGIN_URL +
      '?return_url=' +
      encodeURIComponent(
        location.origin + '/api/login?backurl=' + window.location.href
      );
    return url;
  };
  const getSignupURL = () => {
    const url = 'https://web.dropshipzone.com.au/get-started/sign-up';
    return url;
  };
  useEffect(() => {
    setLoginURL(getLoginURL());
    setSignupURL(getSignupURL());
  }, []);
  useEffect(() => {
    loginTipsVisible && defaultCollapse && setExpand(false);
  }, [loginTipsVisible, defaultCollapse]);

  const handleInputKeyDown = (event: any) => {
    const keyCode = event.keyCode || event.which;
    const keyValue = String.fromCharCode(keyCode);
    const eventKey = event.key;
    // check number key (event.keyCode or event.whic or event.key is number)
    // check keyCode is del(46) or backspace(8) or left(37) or right(39) or tab(9) or
    // console.log(keyCode, keyValue, eventKey);
    if (
      /\d/.test(keyValue) ||
      /\d/.test(eventKey) ||
      [8, 46, 37, 39, 9].includes(keyCode)
    ) {
      return;
    }
    event.preventDefault();
  };

  const handleInput = (event: any) => {
    // check only number
    // console.log(event.currentTarget.value);
    if (event.currentTarget.value && !/^\d+$/.test(event.currentTarget.value)) {
      event.currentTarget.value = event.currentTarget.value.replace(
        /[^0-9]/g,
        ''
      );
    }
  };

  const handleInputPaste = (event: any) => {
    // get paste clipboard data
    const pastedData = event.clipboardData.getData('text/plain');
    // check only number
    if (!/^\d+$/.test(pastedData)) {
      event.preventDefault();
    }
  };

  const handleInputChange = (event: any) => {
    // console.log('change:: ', event.currentTarget.value);
    const val = parseInt(event.currentTarget.value)
      ? String(parseInt(event.currentTarget.value))
      : parseInt(event.currentTarget.value) == 0
        ? '0'
        : '';
    if (String(val).length < 8) {
      event.target.name == 'minPrice' ? setMinPrice(val) : setMaxPrice(val);
    }
  };

  const handleApplyPrice = (e: any) => {
    if (!minPrice && !maxPrice) {
      onChange && onChange('del', { datakey: 'price' });
    } else {
      const priceObj = {
        datakey: 'price',
        type: 'price',
        title: '',
        value: minPrice + '-' + maxPrice,
      };
      if (minPrice === '' && maxPrice !== '') {
        priceObj.title = 'Price < ' + formatCurrency(maxPrice, 0);
      } else if (minPrice !== '' && maxPrice === '') {
        priceObj.title = 'Price >' + formatCurrency(minPrice, 0);
      } else {
        priceObj.title =
          'Price: ' +
          formatCurrency(minPrice, 0) +
          ' - ' +
          formatCurrency(maxPrice, 0);
      }
      onChange && onChange('add', priceObj);
    }
  };

  const getCurrentFilterByKey = (key: any) => {
    if (filtersData && filtersData[key] != undefined) {
      return filtersData[key].value;
    }
    return null;
  };

  const changeFiltersView = () => {
    const priceVal = getCurrentFilterByKey('price');
    if (priceVal) {
      const valArr = priceVal.split('-');
      setMinPrice(valArr[0]);
      setMaxPrice(valArr[1]);
    }
  };
  const filterChangeRef = useRef(changeFiltersView);
  filterChangeRef.current = changeFiltersView;

  useEffect(() => {
    filterChangeRef.current();
  }, [filtersData]);

  return (
    <div className="side-section">
      <div className="side-section-title" onClick={toogleExpand}>
        <span>{title}</span>
        <span
          className={`side-section-expand-icon iconfont icon-expand-line ${expand ? 'expand-icon-up' : 'expand-icon-down'}`}
        ></span>
      </div>
      <div
        className={`side-section-content thin-scroll-bar ${expand ? 'content-expand' : 'content-collapse'}`}
      >
        <div className="side-section-list">
          {loginTipsVisible ? (
            <div className="side-section-login-tips">
              <Link href={signupURL}>Sign up</Link> or{' '}
              <Link href={loginURL}>Login</Link> to use this feature.
            </div>
          ) : (
            data && (
              <div className="side-section-row">
                <div className="side-section-item-input-number">
                  <span className="side-section-item-input-prefix">$</span>
                  <input
                    onKeyDown={handleInputKeyDown}
                    onInput={handleInput}
                    onPaste={handleInputPaste}
                    onChange={handleInputChange}
                    name="minPrice"
                    type="text"
                    value={minPrice}
                    placeholder="Min price"
                  />
                </div>

                <div className="side-section-item-input-number">
                  <span className="side-section-item-input-prefix">$</span>
                  <input
                    onKeyDown={handleInputKeyDown}
                    onInput={handleInput}
                    onPaste={handleInputPaste}
                    onChange={handleInputChange}
                    name="maxPrice"
                    type="text"
                    value={maxPrice}
                    placeholder="Max price"
                  />
                </div>

                <button
                  className="side-section-item-input-button"
                  data-datakey={datakey}
                  data-title={title}
                  data-type={'range'}
                  onClick={handleApplyPrice}
                >
                  Apply
                </button>
              </div>
            )
          )}
        </div>
      </div>
    </div>
  );
};

export default FilterPrice;
